#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import os

from dws.commons.common import check_path_valid, check_sh_cmd_param, empty_dir, log, dws_exec_cmd_by_type
from common.util.cmd_utils import cmd_format
from dws.commons.const import CopyGenerateType
from dws.commons.function_tool import log_start, out_result, progress_notify
from dws.commons.job_info import CopyInfo, JobInfo


class DeleteCopy:

    def __init__(self, pid):
        self._pid = pid

    @log_start()
    def clear_machine_dir(self, job_info: JobInfo, copy_info: CopyInfo):
        del_dir = os.path.join(copy_info.metadata_destination, "roach", f"{copy_info.backup_key}*")
        if not check_sh_cmd_param(del_dir):
            log.error(f"Invalid param of delete dir [{del_dir}], {job_info.log_format()}.")
            return False
        del_cmd = f"gs_ssh -c \\\"rm -rf {del_dir}\\\""
        ret, std_out = dws_exec_cmd_by_type(job_info.usr, job_info.env_path, del_cmd)
        if not ret:
            log.error(f"Delete copy [{copy_info.backup_key}] failed, std_err:{std_out}, {job_info.log_format()}.")
            return False
        log.info(f"Delete copy [{copy_info.backup_key}] success, {job_info.log_format()}.")
        return True

    @log_start()
    @out_result()
    @progress_notify()
    def delete_copies(self, job_info: JobInfo, all_del_copies: list):
        """
        尽最大可能的清除副本记录
        """
        del_success = True
        for copy_info in all_del_copies:
            if copy_info.backup_tool_type != CopyGenerateType.GENERATE_BY_GDS and \
                not self.clear_machine_dir(job_info, copy_info):
                del_success = False
            if not empty_dir(copy_info.meta_path):
                log.warning(f"Empty meta path [{copy_info.meta_path}] failed, {job_info.log_format()}.")
                del_success = False
            for data_rep in copy_info.data_reps:
                data_path = data_rep.get("path")[0]
                if not empty_dir(data_path):
                    log.warning(f"Empty data path [{data_path}] failed, {job_info.log_format()}.")
                    del_success = False

        return del_success
